# lock example unit4 P149

from atexit import register
from random import randrange
from threading import Thread,currentThread,Lock
from time import ctime,sleep

class CleanOutputSet(set):
    def __str__(self):
        return ', '.join(x for x in self)

loops = (randrange(2,5) for x in range(randrange(3,7)))
remaining = CleanOutputSet()
lock = Lock()

def loop(nesc):
    myname = currentThread().name
    lock.acquire() #acquire lock
    remaining.add(myname)
    print('[%s] Started %s' %(ctime(),myname))
    lock.release()
    sleep(nesc)
    lock.acquire()
    remaining.remove(myname)
    print('[%s] completed %s (%d secs)' %(ctime(),myname,nesc))
    print('   (remaining: %s)' % (remaining or 'NONE'))
    lock.release()

def main():
    for pause in loops:
        Thread(target=loop,args=(pause,)).start()

@register
def _atexit():
    print ('all DONE at:', ctime())
    
if __name__ == '__main__':
    main()